<?php

/**

  来源：http://www.sucaihuo.com/

 */
if (!empty($_GET['app']) && $_GET['app'] == 'lottery_json') {
    return lottery_json();
}

/**
 * 中奖机率计算
 */
function lottery_json() {
    //奖品设置
    $prizes = array(
        0 => array(
            "id" => 0, //中奖id
            "name" => "谢谢参与", //奖品名称
            "count" => "0", //库存
        ),
        1 => array(
            "id" => 1,
            "name" => "一等奖免费设计",
            "count" => "10000",
        ),
        2 => array(
            "id" => 2,
            "name" => "四等奖1500代金券",
            "count" => "10000",
        ),
        3 => array(
            "id" => 3,
            "name" => "二等奖500代金券",
            "count" => "10000",
        ),
        4 => array(
            "id" => 4,
            "name" => "三等奖1000代金券",
            "count" => "10000",
        ),
        5 => array(
            "id" => 5,
            "name" => "四等奖1500代金券",
            "count" => "10000",
        ),
        6 => array(
            "id" => 6,
            "name" => "三等奖1000代金券",
            "count" => "100000",
        ),
    );
    $i = 1;
    foreach ($prizes as $v) {
        $proArr[$i] = $v['id']; //奖品id
        $proCount[$i] = $v['count']; //奖品库存动态
        $i++;
    }
    $data = array(
        '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 0
    );

    $rid = getRand($proArr, $proCount);

    if ($rid > 6) {
        $rid = 2;
    } else {
        $rid = returnRid($rid, $data, $proCount, $proArr);
    }
    $rname = "";
    foreach ($prizes as $v) {
        if ($v['id'] == $rid) {
            $rname = $v['name'];
            break;
        }
    }
    echo json_encode(array("rid" => $rid, "rname" => $rname));
}

function returnRid($rid, $data, $proCount, $proArr) {
    $data[$rid] = $data[$rid] + 1;
    $count = $proCount[$rid]; // 总库存
    if ($count < $data[$rid]) {
        // 如果抽取的数据大于总库存时库存清0
        $proCount[$rid] = 0;
        // 然后继续计算一直计算出某个值的库存不为0
        $rid = returnRid($rid, $data, $proCount, $proArr);
    }
    return $rid;
}

/**
 * 中奖概率计算, 能用
 * $proArr = array('1'=>'概率', '2'=>'概率');
 * $proCount = array('1'=>'库存', '2'=>'库存');
 */
function getRand($proArr, $proCount) {
    $result = '';
    $proSum = 0;
    foreach ($proCount as $key => $val) {
        if ($val <= 0) {
            continue;
        } else {
            $proSum = $proSum + $proArr[$key];
        }
    }
    foreach ($proArr as $key => $proCur) {
        if ($proCount[$key] <= 0) {
            continue;
        } else {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
    }
    unset($proArr);
    return $result;
}
